/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package p2a;

import java.io.File;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


/**
 *
 * @author user
 */
public class XMLRulesParser {

   
    public static Vector<Rule> parseFromFile(String fileName) {   
 
        Vector<Rule> result = new Vector();
	  try {
		File fXmlFile = new File(fileName);
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
                
		//System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
		NodeList nList = doc.getElementsByTagName("rule");
		//System.out.println("-----------------------");
		for (int temp = 0; temp < nList.getLength(); temp++) {
 
		   Node nNode = nList.item(temp);
		   if (nNode.getNodeType() == Node.ELEMENT_NODE) {
 
		      Element eElement = (Element) nNode;
                      Rule r = new Rule();
                      r.setOrder(Integer.parseInt(getTagValue("order", eElement)));
                      r.setProtocol(getTagValue("protocol", eElement));
                      r.setSrcIp(getTagValue("src_ip", eElement));
                      r.setSrcPort(getTagValue("src_port", eElement));
                      r.setDestIp(getTagValue("dest_ip", eElement));
                      r.setDestPort(getTagValue("dest_port", eElement));
                      r.setAction(getTagValue("action", eElement));
                      
                      result.add(r);
                      /*
		      System.out.println("order : " + getTagValue("order", eElement));
		      System.out.println("protocol : " + getTagValue("protocol", eElement));
	              System.out.println("src_ip : " + getTagValue("src_ip", eElement));
		      System.out.println("src_port : " + getTagValue("src_port", eElement));
                      System.out.println("dest_ip : " + getTagValue("dest_ip", eElement));
		      System.out.println("dest_port : " + getTagValue("dest_port", eElement));
                      System.out.println("action : " + getTagValue("action", eElement));
                      */
		   }
                   
		}
	  } catch (Exception e) {
		e.printStackTrace();
	  }
          return result;
  }
 
  private static String getTagValue(String sTag, Element eElement) {
	NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
 
        Node nValue = (Node) nlList.item(0);
 
	return nValue.getNodeValue();
  }
 
}